<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>图形绘制之编辑几何图形</title>
    <link rel="stylesheet" href="../v6.4.3/css/ol.css">
    <link rel="stylesheet" href="css/common.css">
  </head>
  <body>
    <div id="map" style="height: 90%;"></div>
    <label>Shape type &nbsp;</label>
    <select name="" id="type">
      <option value="">Select</option>
      <option value="Point">Point</option>
      <option value="LineString">LineString</option>
      <option value="Polygon">Polygon</option>
      <option value="Circle">Circle</option>
      <option value="Square">Square</option>
      <option value="Box">Box</option>
      <option value="None">None</option>
    </select>

    <script src="../v6.4.3/build/ol.js"></script>
    <script>
      //HTMLElement
      let ElSelect = document.getElementById('type')

      //地图
      let mapLayer = new ol.layer.Tile({
        source: new ol.source.OSM()
      })
      //矢量地图
      let vectorSource = new ol.source.Vector()
      let vectorLayer = new ol.layer.Vector({
        source: vectorSource
      })
      let mapView = new ol.View({
        projection: 'EPSG:3857',
        center: [0, 0],
        zoom: 0
      })

      //初始化地图
      let map = new ol.Map({
        target: 'map',
        layers: [mapLayer, vectorLayer],
        view: mapView
      })

      //创建一个 Modify控件
      let draw, snap
      let modify = new ol.interaction.Modify({
        source: vectorSource
      })
      map.addInteraction(modify)
      
      /**
       * @desc 创建 Draw 和 Snap 控件，并加入到 Map对象中
       */
      function addInteractions() {
        draw = new ol.interaction.Draw({
          source: vectorSource,
          type: ElSelect.value
        })
        snap = new ol.interaction.Snap({
          source: vectorSource
        })
        map.addInteraction(draw)
        map.addInteraction(snap)
      }
      
      /**
       * @desc 事件绑定 
       */
      ElSelect.addEventListener('click', () => {
        map.removeInteraction(draw)
        map.removeInteraction(snap)
        addInteractions()
      })
      
    </script>
  </body>
</html>